package com.autohelper.app.tcp.client;

import android.util.Log;


import com.autohelper.app.ActionOperator;
import com.autohelper.app.tcp.cmd.CmdEnum;
import com.autohelper.app.tcp.cmd.RequestRouter;
import com.autohelper.app.tcp.model.Message;
import com.google.gson.Gson;
import com.autohelper.dto.ResultDto;

import java.nio.charset.StandardCharsets;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class ClientHandler extends SimpleChannelInboundHandler<Message> {

    Gson gson = new Gson();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Message msg) throws Exception {
        Log.i("收到消息", "message=" + gson.toJson(msg));

        try {
            RequestRouter.route(msg.getCommand(), new String(msg.getContent(), StandardCharsets.UTF_8), new ActionOperator.IActionCallback() {
                @Override
                public void success(Object data) {
                    if (msg.getCommand() == CmdEnum.SCREEN_CAPTURE.code) {
                        doWriteMessage(ctx, msg, (byte[]) data);
                    } else {
                        ResultDto resultDto = ResultDto.newSuccess(data);

                        String json = gson.toJson(resultDto);
                        byte[] content = json.getBytes(StandardCharsets.UTF_8);
                        doWriteMessage(ctx, msg, content);
                    }
                }

                @Override
                public void fail(String message) {
                    ResultDto resultDto = ResultDto.newError(message);
                    String json = gson.toJson(resultDto);
                    byte[] content = json.getBytes(StandardCharsets.UTF_8);
                    doWriteMessage(ctx, msg, content);
                }
            });
        } catch (Exception e) {
            String json = gson.toJson(ResultDto.newError(e.getMessage()));
            byte[] content = json.getBytes(StandardCharsets.UTF_8);
            doWriteMessage(ctx, msg, content);
        }
    }

    private void doWriteMessage(ChannelHandlerContext context, Message in, byte[] content) {
        Message out = new Message();
        out.setReqId(in.getReqId());
        out.setVersion(in.getVersion());
        out.setCommand(in.getCommand());
        out.setLength(content.length);
        out.setContent(content);

        context.writeAndFlush(out);
    }
}
